package com.kuaimacode.kframework.api.service;

import com.kuaimacode.kframework.api.service.invite.InviteService;
import com.kuaimacode.kframework.api.vo.response.IndexResp;
import com.kuaimacode.kframework.mybatis.models.index.Notice;
import com.kuaimacode.kframework.mybatis.models.invite.Invite;
import com.kuaimacode.kframework.util.DateUtil;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author qinyong
 * @Title:
 * @Package com.kuaimacode.kframework.api.service
 * @Description: created by IntelliJ IDEA
 * @date 2019-03-16 11:14
 */
@Service
public class IndexService {


    @Value("${img.upload.location.root}")
    private String uploadRootLocation;
    @Value("${img.upload.location.img}")
    private String imgUploadLocation;
    @Value("${project.domain}")
    private String domain;

    @Autowired
    private AppMenuService menuService;
    @Autowired
    private SysMessageService messageService;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private SysParamService sysParamService;

    /**
     * 获取首页数据
     *
     * @return
     */
    public IndexResp index(Long userId, Integer userType, String agentId) {
        IndexResp indexResp = new IndexResp();
        //查询菜单数据
        indexResp.setMenus(menuService.getMenu(agentId));
        //查询个人消息数据
        if (userId != null) {
            indexResp.setMessageCount(messageService.getUserUnReadMessageCount(userId, userType));
        }
        //查询公告数据
        List<Notice> notices = Optional.ofNullable(noticeService.getListByAgent(agentId)).orElse(new ArrayList<>());
//        notices.forEach(notice -> notice.setContent(""));
        indexResp.setNotices(notices);

        //查询邀请活动信息
        Invite invite = inviteService.queryAvailableInvite();
        if (invite != null) {
            indexResp.setInviteTitle(invite.getTitle());
        } else {
            invite = inviteService.queryLastInvite();
            if (invite != null) {
                indexResp.setInviteTitle(invite.getTitle());
            }
        }

        //小程序原始id
        String value = sysParamService.findByNameAndAgent("MINI_APP", "000000");
        if(value !=null){
            indexResp.setMiniAppId(value);
        }

        //开通分站url
        String openAgentUrl = sysParamService.findByNameAndAgent("OPEN_AGENT_URL", "000000");
        if(openAgentUrl !=null){
            indexResp.setOpenAgentUrl(openAgentUrl);
        }
        return indexResp;
    }


    /**
     * 发送get请求,  下载图片
     **            路径
     * @return
     */
    public String httpGetImg(CloseableHttpClient client, String imgUrl,String flag) {


        // 发送get请求
        HttpGet request = new HttpGet(imgUrl);
        // 设置请求和传输超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(50000).setConnectTimeout(50000).build();

        //设置请求头
        request.setHeader( "User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1" );

        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                HttpEntity entity = response.getEntity();

                InputStream in = entity.getContent();
                String fileName = DateUtil.getNow(DateUtil.FORMAT_FOUR_MINUTE)+"_"+ flag +".png" ;
                FileUtils.copyInputStreamToFile(in, new File(uploadRootLocation + imgUploadLocation + fileName));
                return fileName;

            }

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            request.releaseConnection();

        }
        return "";
    }
}
